import { _decorator, AudioSource, CacheMode, Component, game, instantiate, Label, Node, ScrollView, Sprite, SpriteFrame, tween, Tween, v3 } from 'cc';
import { GlobalVar } from '../GlobalVar';
import { GameEvent, WssEvent } from '../EventName';
import { HttpCom } from '../net/HttpCom';
import { LandSelectPage } from './LandSelectPage';
import { AdventureRewardProp } from './AdventureRewardProp';
import { AdventureAuction } from './AdventureAuction';
import { ModelUI } from '../ModelUI';
import { WssComAD } from '../net/WssComAD';
import LoopScrollView from './LoopScrollView';
import RankItem from './RankItem';
import { rewardConfig } from './GamePanel';
const { ccclass, property } = _decorator;

class CopperItem extends Component {
    sprite: Sprite = null;
    numLabel: Label = null;
    private guang: Node = null;
    init() {
        this.sprite = this.node.getChildByName("sprite").getComponent(Sprite);
        this.numLabel = this.node.getChildByName("label").getComponent(Label);
        this.guang = this.node.getChildByName("guang");
    }
    setdata() {
        this.scaleForevet(this.sprite.node, 0.5, 1.3, 1);
    }
    scaleForevet(node: Node, runTime: number = 1, scale1, scale2) {
        Tween.stopAllByTarget(node)
        tween()
            .target(node)
            .to(runTime, { scale: v3(scale1, scale1, scale1) })
            .to(runTime, { scale: v3(scale2, scale2, scale2) })
            .union()
            .repeatForever()
            .start()
    }
    protected update(dt: number): void {
        this.guang.angle++;
    }
}

@ccclass('Adventure')
export class Adventure extends Component {

    @property(Label)
    ticketLab: Label = null;

    @property(Node)
    landSelectPage: Node = null;
    @property(Node)
    adventurePanel: Node = null;
    @property(Node)
    adventureDiamondPanel: Node = null;
    @property(Node)
    adventureRewardProp: Node = null;
    @property(Node)
    adventureAution: Node = null;
    @property(Label)
    timeLabel: Label = null;
    @property(Node)
    btnDown: Node = null;
    @property(Node)
    rankContent: Node = null;
    @property(Node)
    rankList: Node = null;
    @property(Node)
    rankItem: Node = null;
    @property(Label)
    jackPotLabel: Label = null;
    @property(SpriteFrame)
    allCopperSprite: SpriteFrame[] = [];
    @property(Node)
    copperItem: Node = null;
    @property(Node)
    allditu: Node = null;

    createTime: number = 0;
    isFirst: boolean = true;

    protected onLoad(): void {
        game.on(GameEvent.USER_INFO_UPDATE, this.updateView, this);
        game.on(WssEvent.ON_ENTER_ADVENTURE_LAND_DATA, this.ON_ENTER_ADVENTURE_LAND_DATA, this);
        game.on(WssEvent.ON_ADVENTURE_DIAMOND, this.ON_ADVENTURE_DIAMOND, this);
        game.on(WssEvent.ON_ADVENTURE_REWARD, this.ON_ADVENTURE_REWARD, this);
        game.on(WssEvent.ON_ADVENTURE_AUCTION, this.onAdventureAuction, this);
    }

    protected onDestroy(): void {
        game.off(GameEvent.USER_INFO_UPDATE, this.updateView, this);
        game.off(WssEvent.ON_ENTER_ADVENTURE_LAND_DATA, this.ON_ENTER_ADVENTURE_LAND_DATA, this);
        game.off(WssEvent.ON_ADVENTURE_DIAMOND, this.ON_ADVENTURE_DIAMOND, this);
        game.off(WssEvent.ON_ADVENTURE_REWARD, this.ON_ADVENTURE_REWARD, this);
        game.off(WssEvent.ON_ADVENTURE_AUCTION, this.onAdventureAuction, this);
    }



    start() {
        // this.initView();
    }

    initView() {
        this.unschedule(this.updateTime)
        this.updateView();
        this.getRank();
    }
    ON_ENTER_ADVENTURE_LAND_DATA(data?: any) {
        console.log(data, "冒险之地数据开始")
        // this.createTime = data.body.timestamp;
        // let nowTime = Date.now();
        // console.log(nowTime, this.createTime, "时间---------------------------")
        // let timestr = Math.floor(60 - (nowTime - this.createTime) / 1000)
        // this.timeLabel.string = String(timestr)
        // this.updateTime();
        // this.schedule(this.updateTime, 1);
    }
    updateTime() {
        let nowTime = Date.now();
        let timestr = Math.floor(60 - (nowTime - this.createTime) / 1000)
        if (timestr < 0) {
            timestr = 0;
        }
        this.timeLabel.string = String(timestr);
        if (timestr <= 0) {
            this.unschedule(this.updateTime);
        }
    }
    ON_ADVENTURE_DIAMOND(data?: any) {
        console.log(data, "爆东西了-------------------")
        let nowdata = data.body;
        game.emit(GameEvent.OPEN_ORE, data);
        for (let i = 0; i < nowdata.length; i++) {
            let node = this.allditu.getChildByName(nowdata[i].area);
            if (node) {
                let item = instantiate(this.copperItem);
                node.addChild(item);
                item.active = true;
                item.setPosition(0, 0, 0);
                if (!item.getComponent(CopperItem)) {
                    item.addComponent(CopperItem);
                    item.getComponent(CopperItem).init();
                }
                item.getComponent(CopperItem).sprite.spriteFrame = this.allCopperSprite[rewardConfig[nowdata[i].coin.name].icon]
                item.getComponent(CopperItem).numLabel.string = nowdata[i].coin.value;
                item.getComponent(CopperItem).setdata();
            }
            if (nowdata[i].coin.name == "DIAMOND_ORE") {
                this.adventureDiamondPanel.active = true;
                this.adventureDiamondPanel.getComponent(AudioSource).play();
                let label = this.adventureDiamondPanel.getChildByName("namelabel").getComponent(Label);
                let numlabel = this.adventureDiamondPanel.getChildByName("numlabel").getComponent(Label);
                label.string = nowdata[i].area;
                numlabel.string = nowdata[i].coin.value + "CT";
            }
        }
    }
    ON_ADVENTURE_REWARD(data?: any) {
        this.adventureRewardProp.active = true;
        this.adventureRewardProp.getComponent(AdventureRewardProp).initPanel(data.body)
    }
    /**推送拍卖信息 */
    onAdventureAuction(data?: any) {
        if (!this.adventureAution.active) {
            this.adventureAution.active = true;
            this.adventureAution.getComponent(AdventureAuction).init(data);
        }
        this.adventureAution.getComponent(AdventureAuction).updateTime(data);
    }
    closeAdventureReward() {
        this.adventureRewardProp.active = false;
    }
    closeAdventureDiamond() {
        this.adventureDiamondPanel.active = false;
    }
    closeAdventureAuction() {
        this.adventureAution.active = false;
    }
    showlandSelectPage() {
        let num = Number(this.ticketLab.string);
        if (num < 22) {
            game.emit(GameEvent.SHOW_TOAST, "Insufficient tickets");
            return;
        }
        let data = {
            cmd: 5
        }
        GlobalVar.wssAD.sendBinaryMessage(data)
        this.landSelectPage.active = true;
        this.landSelectPage.getComponent(LandSelectPage).show();
    }

    protected onEnable(): void {
        HttpCom.getUserInfo();
        //if(!this.isFirst){
        GlobalVar.wssAD = new WssComAD();
        GlobalVar.wssAD.initWs();
        this.isFirst = false;
        //}
    }

    protected onDisable(): void {
        if (GlobalVar.wssAD && GlobalVar.wssAD.socket) {
            GlobalVar.wssAD.socket.close();

        }
    }

    onBuyTicketBtnClick() {
        game.emit(GameEvent.SHOW_STORE_PAGE);
    }

    updateView() {
        this.initPanel();
        this.ticketLab.string = "0";
        GlobalVar.userInfo.walletList.forEach((e, i) => {
            if (e.coin.toLowerCase() == 'ticket') {

                this.ticketLab.string = e.normalBalance.toString();
            }
        })
    }
    initPanel() {
        this.landSelectPage.active = false;
        this.adventurePanel.active = false;
        this.adventureDiamondPanel.active = false;
        this.adventureRewardProp.active = false;
        this.adventureAution.active = false;
    }
    getRank() {
        // HttpCom.getRankHistoryList((data) => {
        //     console.log(data, "----------------排行")
        // })
        HttpCom.getRankList((data) => {
            console.log(data, "----------------排行榜")
            this.jackPotLabel.string = data.jackpot;
            let ranklist = data.rankList;
            let child = this.rankContent.children;
            for (let i = 0; i < child.length; i++) {
                if (ranklist[i]) {
                    child[i].getChildByName("Label").getComponent(Label).string = ranklist[i].username;
                    child[i].getChildByName("numLabel").getComponent(Label).string = ranklist[i].diamond;
                } else {
                    child[i].getChildByName("Label").getComponent(Label).string = "-"
                    child[i].getChildByName("numLabel").getComponent(Label).string = "-";
                }
            }
            this.updateRankList(ranklist);
        })
    }
    openAdventurePanel() {
        this.adventurePanel.active = true;
    }
    closeAdventurePanel() {
        this.adventurePanel.active = false;
    }
    rebackAdventure() {
        this.adventureRewardProp.active = false;
        this.adventureDiamondPanel.active = false;
        ModelUI.getInstance().gamePanel.active = false;
        this.landSelectPage.active = false;
        this.btnDown.active = true;
        HttpCom.getAdventureAward(() => {
            HttpCom.getUserInfo();
        })
    }
    openRankList() {
        this.rankList.active = true;
    }
    closeRankList() {
        this.rankList.active = false;
    }
    private updateRankList(data) {
        let scroll = this.rankList.getChildByName("view").getComponent(ScrollView);
        if (!scroll.node.getComponent(LoopScrollView)) {
            scroll.node.addComponent(LoopScrollView);
            scroll.node.getComponent(LoopScrollView).init(this.rankItem, "rankItem", scroll, 1, 0, RankItem);
        }
        scroll.node.getComponent(LoopScrollView).setData(data);
    }

    update(deltaTime: number) {

    }
}


